/**
 * This program is free software but WITHOUT ANY WARRANTY OR CONDITIONS OF ANY KIND.
 *
 * Copyright (C) 2008-2013 www.pretty-tools.com
 */

/**
 * ObserverService Helper
 */
var yrprxObserverServiceHelper = {
    logger: yrprxFactory.createLogger("yrprxObserverServiceHelper"),
    localObserversTopicToListenersMap: {},
    forwardEventsToContentScript: false
};

yrprxObserverServiceHelper.getListeners = function (topic)
{
    try
    {
        var listeners = this.localObserversTopicToListenersMap[topic];

        if (!listeners)
            this.localObserversTopicToListenersMap[topic] = listeners = [];

        return listeners;
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("getListeners: ", ex);
        return [];
    }
}

yrprxObserverServiceHelper.addObserver = function (observer, topic, ownsWeak)
{
    try
    {
        this.getListeners(topic).push(observer);
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("addObserver: ", ex);
    }
}

yrprxObserverServiceHelper.removeObserver = function (observer, topic)
{
    try
    {
        var listeners = this.getListeners(topic);
        for (var i = 0; i < listeners.length; i++)
            if (listeners[i] == observer)
                listeners.splice(i, 1);
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("removeObserver: ", ex);
    }
}

yrprxObserverServiceHelper.notifyLocalObservers = function (subject, topic, someData)
{
    try
    {
        var listeners = this.getListeners(topic);
        for (var i = 0; i < listeners.length; i++)
        {
            try
            {
                listeners[i].observe(subject, topic, someData);
            }
            catch(e)
            {
                if (this.logger.enabled) this.logger.error("notifyLocalObservers: ", e);
            }
        }
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("notifyLocalObservers: ", ex);
    }
}

yrprxObserverServiceHelper.notifyRemoteObservers = function (subject, topic, someData)
{
    try
    {
        if (someData && someData["clone"])
            someData = someData.clone();

        var port = chrome.extension.connect({name: "ObserverService"});

        port.postMessage({"subject": subject, "topic": topic, "data" : someData});
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("notifyRemoteObservers: ", ex);
    }
}

yrprxObserverServiceHelper.notifyObservers = function (subject, topic, someData)
{
    this.notifyLocalObservers(subject, topic, someData);
    this.notifyRemoteObservers(subject, topic, someData);
}
